package br.com.amadeus.android.activities.course.goal;

import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import br.com.amadeus.android.activities.home.R;
import br.com.amadeus.android.business.FacadeAmadeusDroid;
import br.com.amadeus.android.entities.Course;
import br.com.amadeus.android.entities.CourseUser;
import br.com.amadeus.android.entities.Goal;
import br.com.amadeus.android.util.Util;

public class FormGoalActivity extends Activity
{
	protected static final String CATEGORIA = "curso";
	
	private Button btnSave;
	private EditText edtGol;
	private Button btnExit;
	/*private Intent itExit;*/
	private Intent itHomeGoal;
	private FacadeAmadeusDroid facade = new FacadeAmadeusDroid();


	private Button mPickDate;
	private int mYear;
	private int mMonth;
	private int mDay;
	static final int DATE_DIALOG_ID = 0;

	private Button mPickDateFinish;
	private int mYearFinish;
	private int mMonthFinish;
	private int mDayFinish;
	static final int DATE_DIALOG__FINAL_ID = 2;

	private Button mPickTime;
	private int mHour;
	private int mMinute;
	static final int TIME_DIALOG_ID = 1;

	private Button mPickTimeFinish;
	private int mHourFinish;
	private int mMinuteFinish;
	static final int TIME_DIALOG_FINAL_ID = 4;

	private Button mPickTimeHourDay;
	private int mHourDay;
	private int mMinuteDay;
	static final int TIME_DIALOG_TEMPODIARIO_ID = 5;
	
	StringBuilder sbBeginDate = new StringBuilder();
	StringBuilder sbEndDate = new StringBuilder();
	StringBuilder sbBeginTime = new StringBuilder();
	StringBuilder sbEndTime = new StringBuilder();
	StringBuilder sbAvgStudy = new StringBuilder();
	int avgTime;
	private int course_user_id;
	int course_id;
	int goal_id = 0;


	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_objetivo);
		
		initComponents();
				
		Bundle gotBasket = getIntent().getExtras();
				
		int id_goal = 0;
		id_goal = gotBasket.getInt("goal_id");
		if (id_goal == 0) {
			
			course_id = gotBasket.getInt("course_id");
			Course course = facade.getCourse(course_id);
			course_user_id = facade.getCourseUser(course.getId_amadeus());
			
			fillFormGoal();
			
		}else{
			Goal goal = facade.getGoal(id_goal);
			updateFormGoal(goal);
		}
		
		/*btnNew.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) 
			{
				startActivity(itNew);
			}
		});*/


		btnSave.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) 
			{
				StringBuilder beginDate = sbBeginDate.append(sbBeginTime.toString());
				StringBuilder endDate = sbEndDate.append(sbEndTime.toString());
				
				Goal goal = new Goal(goal_id, edtGol.getText().toString(), beginDate.toString(), endDate.toString(),
						avgTime, new CourseUser(course_user_id), false);
				facade.insertGoal(goal);
				
				//Recupera o Curso
				int amadeus_id_course = facade.getCourseByCourseUser(course_user_id);
				Course course = facade.getCourseByAmadeusId(amadeus_id_course);
				itHomeGoal.putExtra("course_id", course.getId());
				startActivity(itHomeGoal);
				
			}
		});


		btnExit.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) 
			{			
				//Recupera o Curso
				int amadeus_id_course = facade.getCourseByCourseUser(course_user_id);
				Course course = facade.getCourseByAmadeusId(amadeus_id_course);
				itHomeGoal.putExtra("course_id", course.getId());
				startActivity(itHomeGoal);
			}
		});

		//-------------------------------------------------------------------------------------------//
		//display data inicial

		
		// add a click listener to the button
		mPickDate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});


		//-------------------------------------------------------------------------------------------//

		//-------------------------------------------------------------------------------------------//
		//display data final

		// add a click listener to the button
		mPickDateFinish.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DATE_DIALOG__FINAL_ID);
			}
		});

		
		//-------------------------------------------------------------------------------------------//

		// add a click listener to the button
		mPickTimeHourDay.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(TIME_DIALOG_TEMPODIARIO_ID);
			}
		});

		
		// add a click listener to the button
		mPickTime.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(TIME_DIALOG_ID);
			}
		});

		//-------------------------------------------------------------------------------------------//

		//-------------------------------------------------------------------------------------------//		
		//display de horas final

		
		// add a click listener to the button
		mPickTimeFinish.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) {
				showDialog(TIME_DIALOG_FINAL_ID);
			}
		});

		//-------------------------------------------------------------------------------------------//

	}//fim construtor
	
	private void fillFormGoal() {
		
		//-------------------------------------------------------------------------------------------//
		//display data inicial
		
		// get the current date
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);

		// Display de datas
		updateDisplayDates();
		
		//-------------------------------------------------------------------------------------------//
		//display data final
		
		// get the current date
		final Calendar c2 = Calendar.getInstance();
		mYearFinish = c2.get(Calendar.YEAR);
		mMonthFinish = c2.get(Calendar.MONTH);
		mDayFinish = c2.get(Calendar.DAY_OF_MONTH);

		updateDisplayDatesFinal();
		
		// get the current time
		mHourDay = 0;
		mMinuteDay = 0;
		
		//-------------------------------------------------------------------------------------------//		
		//display de horas inicial
		updateDisplayTimerTempoDiario();
		
		// get the current time
		final Calendar c1 = Calendar.getInstance();
		mHour = c1.get(Calendar.HOUR_OF_DAY);
		mMinute = c1.get(Calendar.MINUTE);

		updateDisplayTimer();
		
		final Calendar c3 = Calendar.getInstance();
		mHourFinish = c3.get(Calendar.HOUR_OF_DAY);
		mMinuteFinish = c3.get(Calendar.MINUTE);

		// display the current date
		updateDisplayTimerFinal();
		
	}

	private void initComponents() {
			
		itHomeGoal = new Intent(this, HomeGoalActivity.class);
		/*itExit = new Intent(this, HomeGoalActivity.class);*/
		
		itHomeGoal.putExtra("course_id", course_id);

		btnSave = (Button)findViewById(R.id.imgBtnSalvar);
		btnExit = (Button)findViewById(R.id.imgBtnSair);

		edtGol = (EditText)findViewById(R.id.edtObjetivo);
		
		mPickDate = (Button) findViewById(R.id.pickDate);
		
		mPickDateFinish = (Button) findViewById(R.id.pickDateFinal);
		
		mPickTimeHourDay = (Button) findViewById(R.id.pickTimeTempoDiario);
		
		mPickTime = (Button) findViewById(R.id.pickTime);
		
		mPickTimeFinish = (Button) findViewById(R.id.pickTimeFinal);
		
	}

	private void updateFormGoal(Goal goal) {
		
		this.course_user_id = goal.getCourseUser().getId();
		this.goal_id = goal.getId();
		this.edtGol.setText(goal.getDefinition());
		
		//Data inicial
		final Calendar c = Calendar.getInstance();
		Date initialDate = Util.getDate(goal.getBeginDate(), Util.FORMATO_DATA_UI);
		c.setTime(initialDate);
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		
		updateDisplayDates();
		
		//Data final
		final Calendar c2 = Calendar.getInstance();
		Date finalDate = Util.getDate(goal.getEndDate(), Util.FORMATO_DATA_UI);
		c2.setTime(finalDate);
		mYearFinish = c2.get(Calendar.YEAR);
		mMonthFinish = c2.get(Calendar.MONTH);
		mDayFinish = c2.get(Calendar.DAY_OF_MONTH);

		updateDisplayDatesFinal();
		
		//Hora inicial
		// get the current time
		final Calendar c1 = Calendar.getInstance();
		c1.setTime(initialDate);
		mHour = c1.get(Calendar.HOUR_OF_DAY);
		mMinute = c1.get(Calendar.MINUTE);

		updateDisplayTimer();
				
		//Tempo diário de estudo
		int avg_study = goal.getAvgStudyTime();
		int hour = avg_study / 60;
		int minute = avg_study - (hour * 60);
		
		mHourDay = hour;
		mMinuteDay = minute;
				
		//display de horas inicial
		updateDisplayTimerTempoDiario();
		
		//Hora final
		final Calendar c3 = Calendar.getInstance();
		c3.setTime(finalDate);
		mHourFinish = c3.get(Calendar.HOUR_OF_DAY);
		mMinuteFinish = c3.get(Calendar.MINUTE);

		// display the current date
		updateDisplayTimerFinal();
		
		//Recupera o Curso
		int amadeus_id_course = facade.getCourseByCourseUser(course_user_id);
		Course course = facade.getCourseByAmadeusId(amadeus_id_course);
		itHomeGoal.putExtra("course_id", course.getId());
				
	}

	@Override
	protected void onStop() {
		super.onStop();
		finish();
	}

	//atualiza os dados do calendário
	private void updateDisplayDates() 
	{
		String zeroMes = "";
		String zeroDia = "";

		if(mMonth < 10)
		{
			zeroMes = "0";
		}
		if(mDay < 10)
		{
			zeroDia = "0";
		}

		//atualizando o lable do botão
		//
		
		StringBuilder sbBeginDateTemp = new StringBuilder();
		sbBeginDateTemp.append(zeroDia).append(mDay).append("/")
		.append(zeroMes).append(mMonth + 1).append("/")
		.append(mYear).append(" ");
		sbBeginDate.replace(0, 12, sbBeginDateTemp.toString());
		mPickDate.setText(sbBeginDate);
	}


	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() 
	{
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) 
		{
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDisplayDates();
		}
	};


	private void updateDisplayTimer() 
	{
		String zeroHora = "";
		String zeroMinuto = "";

		if(mHour < 10)
		{
			zeroHora = "0";
		}

		if(mMinute < 10)
		{
			zeroMinuto = "0";
		}
		StringBuilder sbBeginTimeTemp =  new StringBuilder();
		sbBeginTimeTemp.append(zeroHora).append(mHour).append(":")
		.append(zeroMinuto).append(mMinute);
		sbBeginTime.replace(0, 5, sbBeginTimeTemp.toString());
		mPickTime.setText(sbBeginTime.toString());
	}

	private void updateDisplayTimerTempoDiario() 
	{
		String zeroHora = "";
		String zeroMinuto = "";

		if(mHourDay < 10)
		{
			zeroHora = "0";
		}
		if(mMinuteDay < 10)
		{
			zeroMinuto = "0";
		}
		int hm = mHourDay*60;
		int m = mMinuteDay;
		avgTime  = hm+m;
		StringBuilder sbAvgStudyTemp =  new StringBuilder();
		sbAvgStudyTemp.append(zeroHora).append(mHourDay).append(":")
		.append(zeroMinuto).append(mMinuteDay);
		sbAvgStudy.replace(0, 5, sbAvgStudyTemp.toString());
		mPickTimeHourDay.setText(sbAvgStudy.toString());
	}

	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() 
	{
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) 
		{
			mHour = hourOfDay;
			mMinute = minute;
			updateDisplayTimer();
		}
	};

	//-------------------------------------------------------------------------------------------//		
	//display de data final

	private void updateDisplayDatesFinal() 
	{
		String zeroMes = "";
		String zeroDia= "";

		if(mMonthFinish < 10)
		{
			zeroMes = "0";
		}
		if(mDayFinish < 10)
		{
			zeroDia = "0";
		}
		
		//atualizando o lable
		StringBuilder sbEndDateTemp = new StringBuilder();
		sbEndDateTemp.append(zeroDia).append(mDayFinish).append("/")
		.append(zeroMes).append(mMonthFinish + 1).append("/")
		.append(mYearFinish).append(" ");
		sbEndDate.replace(0, 12, sbEndDateTemp.toString());
		mPickDateFinish.setText(sbEndDate);
	}


	private DatePickerDialog.OnDateSetListener mDateSetListenerFinal = new DatePickerDialog.OnDateSetListener() 
	{
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) 
		{
			mYearFinish = year;
			mMonthFinish = monthOfYear;
			mDayFinish = dayOfMonth;
			updateDisplayDatesFinal();
		}
	};

	//-------------------------------------------------------------------------------------------//		


	//-------------------------------------------------------------------------------------------//		
	//display timer final
	private void updateDisplayTimerFinal() 
	{
		String zeroHora = "";
		String zeroMinuto = "";

		if(mHourFinish < 10)
		{
			zeroHora = "0";
		}

		if(mMinuteFinish < 10)
		{
			zeroMinuto = "0";
		}
		
		StringBuilder sbEndTimeTemp =  new StringBuilder();
		sbEndTimeTemp.append(zeroHora).append(mHourFinish).append(":")
		.append(zeroMinuto).append(mMinuteFinish);
		sbEndTime.replace(0, 5, sbEndTimeTemp.toString());
		mPickTimeFinish.setText(sbEndTime.toString());
	}


	private TimePickerDialog.OnTimeSetListener mTimeSetListenerTempoDiario = new TimePickerDialog.OnTimeSetListener() 
	{
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) 
		{
			mHourDay = hourOfDay;
			mMinuteDay = minute;
			updateDisplayTimerTempoDiario();
		}
	};



	private TimePickerDialog.OnTimeSetListener mTimeSetListenerFinal = new TimePickerDialog.OnTimeSetListener() 
	{
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) 
		{
			mHourFinish = hourOfDay;
			mMinuteFinish = minute;
			updateDisplayTimerFinal();
		}
	};


	@Override
	protected Dialog onCreateDialog(int id) 
	{
		switch (id) 
		{
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);

		case DATE_DIALOG__FINAL_ID:
			return new DatePickerDialog(this, mDateSetListenerFinal, mYearFinish, mMonthFinish, mDayFinish);

		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, mTimeSetListener,mHour, mMinute, false);

		case TIME_DIALOG_FINAL_ID:
			return new TimePickerDialog(this, mTimeSetListenerFinal,mHourFinish, mMinuteFinish, false);

		case TIME_DIALOG_TEMPODIARIO_ID:
			return new TimePickerDialog(this, mTimeSetListenerTempoDiario,mHourDay, mMinuteDay, true);
		}

		return null;
	}

}